﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using System.Data;
using System.ComponentModel.Composition;

namespace IRM.Messaging.Repository
{
    [Export(typeof(IMessagesDataContext))]
    public class SqlMessagesDataContext : SqlDataContext, IMessagesDataContext
    {
        public SqlMessagesDataContext(string connectionString) 
            : base(connectionString)
        {
        }

        public SqlMessagesDataContext(IDbConnection connection)
            : base(connection)
        {
        }

        public IQueryable<Message> Messages
        {
            get
            {
                return this.GetTable<Message>();
            }
        }

        public void SaveStatus(Message message)
        {
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                SubmitChanges();
                scope.Complete();
            }
        }
    }

    [Export(typeof(IDataContext))]
    public class SqlDataContext : System.Data.Linq.DataContext, IDataContext
    {
        public SqlDataContext(string connectionString) 
            : base(connectionString)
        {
        }

        public SqlDataContext(IDbConnection connection)
            : base(connection)
        {
        }

        public void Attach<T>(T entity, T original)
            where T : class
        {
            this.GetTable<T>().Attach(entity, original);
        }

        public void Insert<T>(T entity)
            where T : class
        {
            this.GetTable<T>().InsertOnSubmit(entity);
        }

        public void Remove<T>(T entity)
            where T : class
        {
            this.GetTable<T>().DeleteOnSubmit(entity);
        }

    }
}
